$(function ($) {

    var href = window.location.href;
    //console.log("href = " + href);

    var host = window.location.host;

    if (host == "item.m.jd.com") {
        var skuId = $("#currentWareId").val();

        console.log("Current host is item.m.jd.com");
        var startTime = window.sessionStorage.getItem(skuId+"_startTime");
        if(startTime != undefined) {
            var timestamp = (new Date()).valueOf();
            if(timestamp < startTime) {
                console.log("sleep 60... waiting timer.")
                setTimeout("location.reload()", 60000);
                return;
            }
        }

        var product = window.location.pathname.split("/")[1]
        if(product == "product") {
            window.sessionStorage.setItem("href", href);
        }


        if ($("#type").val() == "1") {
            //抢购
            //console.log("点击按钮[立即抢购]");
            document.querySelector('#add_cart').click();
            return;
        }


        
        var jdPrice = $("#jdPrice").val();

        if (skuId == undefined || jdPrice == undefined) {
            //console.log("skuId = " + skuId + " jdPrice = " + jdPrice + " is Error!")
            return;
        }

        var oldPrice = window.sessionStorage.getItem(skuId);
        if (oldPrice == undefined) {
            window.sessionStorage.setItem(skuId, jdPrice);
            delayReload();
            return;
        }


        if (jdPrice == oldPrice) {
            delayReload();
            return;
        }

        //普通
        //console.log("点击按钮[立即购买]");
        document.querySelector('#directorder').click()
        return;

    } else if (host == "p.m.jd.com") {
        //购物车页面 OR
        //console.log("Current host is p.m.jd.com");
        purchaseInCat();

    } else if (host == "marathon.jd.com") {
        //console.log("Current host is marathon.jd.com");
        scareBuy(host);

    } else if (host == "bolt.jd.com") {
        //console.log("Current host is bolt.jd.com");
        scareBuy(host);
    }
});

function readCookie(name){
    var cookieValue = "";
    var search = name + "=";
    if(document.cookie.length > 0){
        offset = document.cookie.indexOf(search);
        if (offset != -1){
             offset += search.length;
             end = document.cookie.indexOf(";", offset);
             if (end == -1) 
                 end = document.cookie.length;
             cookieValue = (document.cookie.substring(offset, end));
        }
    }
    return cookieValue;
}

function forward2SiglePage(skuid){
    window.location.href = "http://item.m.jd.com/product/"+skuid+".html";
}

function scareBuy(host) {

    if (window.location.pathname == "/seckillM/seckill.action") {
        if ($("#submitBtn").size() != 0) {
            //console.log("Selector[#submitBtn] has found!")
            document.querySelector('#submitBtn').click();
        } else {
            //console.log("Selector[#submitBtn] is not found!Please Check!")
        }
        return;
    }

    if (window.location.pathname == "/m/captcha.html") {
        setTimeout("submitOrderInBolt('"+host+"')", 0);
        //submitOrderInBolt(host);
        return;
    }

    if (window.location.pathname == "/mobile/koFail.html") {
        if($("#tryBtn").size() != 0 ) {
            document.querySelector('#tryBtn').click();
            //return;
        }

        var skuId = readCookie("seckillSku");
        //var sid = readCookie("seckillSid");

        //console.log("skuId = " + skuId + " in koFail.html")
        window.location.href = "http://item.m.jd.com/product/"+skuId+".html";
        return;
    }
}


function delayReload() {
    setTimeout("location.reload()", 0);
}

//[提交订单]按钮
// p.m.jd.com
function purchaseInCat() {
    if ($("a div.pay-leak-btn-red").size() != 0) {
        // 在线支付 按钮
        //console.log("Selector[a div.pay-leak-btn-red] has found!")
        document.querySelector('a div.pay-leak-btn-red').click();
    } else {
        console.error("Selector[a div.pay-leak-btn-red] is not found!Please Check!")
    }
}


// 这有可能是独立秒杀流程
// 单品页变成抢购抢购按钮时会走到这里
function submitOrderInBolt(host) {
    var skuId = $("#skuId").val();
    var sid = $("#sid").val();
    //console.log("skuid = " + skuId + " sid = " + sid);
    var kourl = "http://" + host + "/validateM/repeatGoToOrder?skuId=" + skuId + "&sid=" + sid;
    jQuery.ajax( {
        type : "POST",
        dataType : "json",
        crossDomain: true,
        url : kourl,
        data : null,
        cache : false,
        success : function(data) {
            if (isEmpty(data)) {
                console.log("status isEmpty")
                forward2SiglePage(skuId)
                return;
            }
            if (data.code == "200") {
                console.log("status 200 data.url = " + data.url)
                window.location.href = data.url;
                return;
            }else if(data.code == "402"){
                console.log("status 402")
                forward2SiglePage(skuId)
                return;
            }else if(data.code == "403"){
                console.log("status 403 data.url = " + data.url)
                //forward2SiglePage(skuId)
                setTimeout("submitOrderInBolt(\""+host+"\")",0);
                return;
            }else{
                console.log("status other")
                forward2SiglePage(skuId)
                return;
            }
        },
        error : function(XMLHttpResponse) {
            console.log("status error")
            setTimeout("submitOrderInBolt(\""+host+"\")",0);

            //forward2SiglePage(skuId);
            return;
        }
    });
}

// marathon.jd.com
// 提交订单
function submitOrder() {
    if ($("#submitBtn").size() != 0) {
        //console.log("Selector[#submitBtn] has found!")
        document.querySelector('#submitBtn').click();
    } else {
        //console.log("Selector[#submitBtn] is not found!Please Check!")
    }
}

// 单品页加抢购
// 立即抢购 按钮代码
//<a class="red-color" id="add_cart"> 立即抢购   </a>
// 立即购买 按钮代码
//<a class="red-color " id="directorder" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1);">立即购买</a>
//
// item.m.jd.com
function purchaseInSinglePage() {
    if ($("#add_cart.red-color").size() != 0) {
        //console.log("发现按钮[立即抢购]");
        document.querySelector('#add_cart').click();
    } else if ($("#directorder.red-color").size() != 0) {
        //console.log("发现按钮[立即购买]");
        document.querySelector('#directorder').click()
    } else {
        //console.log("单品页[item.m.jd.com]未发现提购买按钮！please check!")
    }
}

/**
 * 判断是否是空
 * @param value
 */
function isEmpty(value) {
    if (value == null || value == "" || value == "undefined" || value == undefined || value == "null") {
        return true;
    }
    else {
        if (value instanceof Object) {
            return false;
        }
        value = value.replace(/\s/g, "");
        if (value == "") {
            return true;
        }
        return false;
    }
}
